package cn.guava;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import org.junit.Test;


import cn.datawin.Rule;
import cn.datawin.Rule_Baidu;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class Guava {

	static CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
	
	@Test
	public void cache1() throws InstantiationException, IllegalAccessException{
		LoadingCache<String, Rule> cache = builder
		.maximumSize(10).
		build(
				new CacheLoader<String, Rule>(){
				@Override
				public Rule load(String paramK) throws Exception {
					return createRule(paramK);
				}
			});
		
		Class<? extends Rule> clazz = Rule_Baidu.class;
		Rule_Baidu.class.getName();
		Rule rule =  clazz.newInstance();
		rule.setObject("hello");
		cache.put(clazz.getName(), rule);
		
		Rule rule11 =cache.getUnchecked(Rule_Baidu.class.getName());
		System.out.println("LoadingCache==="+ rule11.getObject(String.class));
		
	}
	
	
	
	@Test
	public void cache2() throws InstantiationException, IllegalAccessException, ExecutionException{
		Cache<String, Rule> cache = builder
		        .build(); 
		Rule rule =  new Rule_Baidu();
		rule.setSerialize("hello");
//		rule.getSerialize();
//		cache.put("rrr", rule);
		rule =  cache.get("rrr", new Callable<Rule>() {
			@Override
			public Rule call() throws Exception {
				return createRule(Rule_Baidu.class.getName());
			}
		});
		cache.invalidate("rrr");
		rule =  cache.get("rrr", new Callable<Rule>() {
			@Override
			public Rule call() throws Exception {
				return createRule(Rule_Baidu.class.getName());
			}
		});
		System.out.println("cache===="+rule.getSerialize());

	}
	
	
	
	
	public Rule createRule(String param) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
		System.out.println("-----findNull-----");
		Rule r = (Rule) Class.forName(param).newInstance();
		r.setSerialize("----finaNull-----");
		return r;
	}
	
	void aa(){
		
		
		
		
	}

	
	
	

}
